<template>
  <el-drawer
    :title="drawerTitle[drawerType]"
    size="60%"
    :visible.sync="drawerVisible"
    direction="rtl"
    :close-on-press-escape="false"
    :wrapperClosable="false"
    :destroy-on-close="true"
    :before-close="clearDialog"
    custom-class="tag-drawer"
    v-drawerResize
  >
    <div class="drawer-wrap">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
          <h4 class="type-title">
            <div class="icon-box"><icon-svg name="iconBase"></icon-svg></div>
            <span>基本信息</span>
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属公司" prop="compId">
                <tag-tree-selection
                  title="所属公司"
                  :data="compTreeList"
                  :treeProps="compTreeProps"
                  :initId="editForm.compId"
                  :editable="editForm.treeLevel === 1"
                  @confirm="id => (editForm.compId = id)"
                ></tag-tree-selection>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级部门" prop="parentDeptId">
                <tag-tree-selection
                  title="上级部门"
                  :data="treeList"
                  :treeProps="treeProps"
                  :initId="editForm.parentDeptId"
                  :editable="editable"
                  @confirm="id => (editForm.parentDeptId = id)"
                ></tag-tree-selection>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptNm">
                <el-input placeholder="请输入部门名称" :readonly="!editable" v-model="editForm.deptNm"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门全称" prop="deptFname">
                <el-input placeholder="请输入部门全称" :readonly="!editable" v-model="editForm.deptFname"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门类型" prop="deptType">
                <el-select v-model="editForm.deptType">
                  <el-option label="--" value=""></el-option>
                  <el-option
                    v-for="item in $dictList('$dept_type')"
                    :key="item.key"
                    :label="item.value"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="principalCnName">
                <el-select v-model="editForm.principalCnName" placeholder="请选择负责人" filterable>
                  <el-option value="" label="--"></el-option>
                  <el-option
                    v-for="item in users"
                    :key="item.userId"
                    :value="item.loginUname"
                    :label="$name(item, 'nname', 'loginUname')"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系地址" prop="contactAddr">
                <el-input placeholder="请输入联系地址" :readonly="!editable" v-model="editForm.contactAddr"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="办公电话" prop="officePhone">
                <el-input placeholder="请输入办公电话" :readonly="!editable" v-model="editForm.officePhone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电子邮箱" prop="deptEmail">
                <el-input placeholder="请输入电子邮箱" :readonly="!editable" v-model="editForm.deptEmail"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮政编码" prop="zipCode">
                <el-input placeholder="请输入邮政编码" :readonly="!editable" v-model="editForm.zipCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注信息" prop="cmntStr">
                <el-input
                  type="textarea"
                  placeholder="请输入备注信息，最大不能超过100个字符"
                  v-model="editForm.cmntStr"
                  :readonly="!editable"
                  :rows="3"
                  resize="none"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns">
      <el-button @click="clearDialog">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-drawer>
</template>

<script>
import tagTreeSelection from '@/components/tag-tree-selection'
import utils from '@/plugins/utils'
export default {
  props: {
    treeList: {
      type: Array,
      default: () => []
    }
  },
  components: {
    tagTreeSelection
  },
  data() {
    return {
      editable: true,
      drawerVisible: false,
      drawerType: 'add',
      drawerTitle: {
        add: '新增',
        edit: '编辑'
      },
      deptId: '',
      deptStatus: '',
      users: [],
      editForm: {
        compId: '',
        parentDeptId: '',
        deptNm: '',
        deptFname: '',
        deptType: '',
        contactAddr: '',
        deptEmail: '',
        officePhone: '',
        principalCnName: '',
        zipCode: '',
        cmntStr: '',
        treeLevel: 1
      },
      editFormRules: {
        deptNm: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { max: 30, message: '部门名称不能超过30个字符', trigger: 'blur' }
        ],
        deptFname: [
          { required: true, message: '部门全称不能为空', trigger: 'blur' },
          { max: 50, message: '部门全称不能超过50个字符', trigger: 'blur' }
        ],
        deptType: [{ required: true, message: '部门类型不能为空', trigger: 'change' }],
        compId: [{ required: true, message: '所属公司不能为空', trigger: 'change' }],
        // principalCnName: [{ required: true, message: '负责人不能为空', trigger: 'change' }],
        contactAddr: [{ max: 50, message: '联系地址不能超过50个字符', trigger: 'blur' }],
        officePhone: [
          { max: 30, message: '办公电话不能超过30个字符', trigger: 'blur' },
          { validator: this.$validator(/^[0-9]{0,}$/, '办公电话只能输入数字'), trigger: 'blur' }
        ],
        deptEmail: [
          { type: 'email', message: '请输入正确的电子邮箱', trigger: 'blur' },
          { max: 30, message: '电子邮箱不能超过30个字符', trigger: 'blur' }
        ],
        zipCode: [
          { max: 20, message: '邮政编码不能超过20个字符', trigger: 'blur' },
          { validator: this.$validator(/^[0-9]{0,}$/, '邮政编码只能输入数字'), trigger: 'blur' }
        ],
        cmntStr: [{ max: 100, message: '备注信息不能超过100个字符', trigger: 'blur' }]
      },
      treeProps: {
        title: '上级部门',
        children: '_children',
        label: 'deptNm',
        id: 'deptId'
      },
      compTreeList: [],
      compTreeProps: {
        title: '所属公司',
        children: '_children',
        label: 'compNm',
        id: 'compId'
      }
    }
  },
  methods: {
    getCompanyList() {
      return new Promise((resolve, reject) => {
        this.$ajax({
          url: this.$ajax.setUrl('auth/authCompMgr/list'),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.compTreeList = utils.arrayToTree(data.data, {
              id: 'compId',
              pid: 'parentCompId',
              mainSort: 'treeLevel'
            })
            resolve()
          } else {
            this.$message.error('获取公司列表失败！')
            reject()
          }
        })
      })
    },
    showDrawer(type, data) {
      this.drawerType = type
      this.getUsers()
      this.getCompanyList().then(() => {
        switch (type) {
          case 'add':
            if (data.deptId) {
              this.editForm.compId = data.compId
              this.editForm.parentDeptId = data.deptId
            }
            this.editable = true
            this.drawerVisible = true
            break
          case 'edit':
            this.editable = true
            this.getDeptDetail(data)
            break
        }
      })
    },
    getUsers() {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authUserMgr/noSysUsers'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.users = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = {
            compId: this.editForm.compId,
            parentDeptId: this.editForm.parentDeptId,
            deptNm: this.editForm.deptNm,
            deptFname: this.editForm.deptFname,
            deptType: this.editForm.deptType,
            contactAddr: this.editForm.contactAddr,
            deptEmail: this.editForm.deptEmail,
            officePhone: this.editForm.officePhone,
            principalCnName: this.editForm.principalCnName,
            zipCode: this.editForm.zipCode,
            cmntStr: this.editForm.cmntStr
          }
          if (this.drawerType === 'edit')
            params = Object.assign({}, params, { deptId: this.deptId, deptStatus: this.deptStatus })
          this.$ajax({
            url: this.$ajax.setUrl('auth/authDeptMgr'),
            method: this.drawerType === 'add' ? 'post' : 'put',
            data: this.$ajax.setData(params)
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.clearDialog()
              this.$emit('refresh')
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message.error(data.data || data.msg)
            }
          })
        }
      })
    },
    getDeptDetail(scope) {
      this.$ajax({
        url: this.$ajax.setUrl('auth/authDeptMgr/' + scope.deptId),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.deptId = data.data.deptId || ''
          this.deptStatus = data.data.deptStatus
          this.editForm.compId = data.data.compId || ''
          this.editForm.parentDeptId = data.data.parentDeptId || ''
          this.editForm.deptNm = data.data.deptNm || ''
          this.editForm.deptFname = data.data.deptFname || ''
          this.editForm.deptType = data.data.deptType
          this.editForm.contactAddr = data.data.contactAddr || ''
          this.editForm.deptEmail = data.data.deptEmail || ''
          this.editForm.officePhone = data.data.officePhone || ''
          this.editForm.principalCnName = data.data.principalCnName || ''
          this.editForm.zipCode = data.data.zipCode || ''
          this.editForm.cmntStr = data.data.cmntStr || ''
          this.editForm.treeLevel = data.data.treeLevel || 1
          this.drawerVisible = true
        } else {
          this.$message('获取部门信息失败！')
        }
      })
    },
    clearDialog() {
      this.deptId = ''
      this.deptStatus = ''
      this.editForm.compId = ''
      this.editForm.parentDeptId = ''
      this.editForm.deptNm = ''
      this.editForm.deptFname = ''
      this.editForm.deptType = ''
      this.editForm.contactAddr = ''
      this.editForm.deptEmail = ''
      this.editForm.officePhone = ''
      this.editForm.principalCnName = ''
      this.editForm.zipCode = ''
      this.editForm.cmntStr = ''
      this.editForm.treeLevel = 1
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
      this.drawerVisible = false
    }
  }
}
</script>

<style lang="scss"></style>
